<template>
    <span @click='open'><slot></slot></span>
    <a-modal v-model:visible='visible' :width='width' :title='props.title' :confirm-loading='loading' :cancelText='props.cancelText' :okText='props.confirmText' @ok='confirm' @cancel='closeModal'>
        <slot name='content'></slot>
    </a-modal>
</template>

<script lang='ts' setup>
    import { nextTick, ref } from 'vue'
    const props = withDefaults(defineProps<{
        width : string|number,
        title : string,
        cancelText? : string,
        confirmText? : string,
        confirm : () => Promise<any>
    }>(), {
        cancelText : '取消',
        confirmText : '确定'
    })

    const emit = defineEmits<{
        (e : 'open'): void,
        (e : 'close'): void
    }>()

    const visible = ref(false)
    const loading = ref(false)

    function closeModal() {
        emit('close')
    }

    function open() {
        visible.value = true
        nextTick(() => {
            emit('open')
        })
    }

    function close() {
        visible.value = false
        closeModal()
    }

    async function confirm() {
        loading.value = true
        await props.confirm()
        loading.value = false
    }

    defineExpose({
        close
    })
</script>
